﻿using System;
using System.Dynamic;
using System.Web;
using EPiServer.Core;
using OpenWaves;
using OpenWaves.EPiServer.Comments.Content.UserDataProviders;
using OpenWaves.EPiServer.Comments.Models.Pages;
using OpenWaves.EPiServer.Comments.Models.Requests;
using OpenWaves.EPiServer.Comments.Models.ValueObjects;

namespace OpenWaves.EPiServer.Comments.Content.DataMappers
{
    public class DefaultCommentDataMapper : ICommentDataMapper
    {
        private readonly IUserDataProvider userDataProvider;

        public DefaultCommentDataMapper()
        {
            this.userDataProvider = ServiceLocator.Resolve<IUserDataProvider>();
        }


        public virtual CommentPage MapCommentToCommentPage(CommentPage targetPage, Comment comment)
        {
            if (targetPage == null || comment == null)
                return targetPage;

            targetPage.CreatedBy = comment.AuthorName;
            targetPage.Created = comment.CreatedOn;
            targetPage.CommentBody = new XhtmlString(comment.CommentBody);
            targetPage.Name = String.Format("{0}, {1}", comment.AuthorName, comment.CreatedOn.ToString("yyyy.MM.dd HH:mm"));

            return targetPage;
        }


        public virtual Comment MapAddCommentRequestToComment(Comment targetComment, AddCommentRequest request)
        {
            if (targetComment == null || request == null)
                return targetComment;

            targetComment.AuthorName = HttpContext.Current.User.Identity.Name;
            targetComment.Author =
                userDataProvider.GetUserData(HttpContext.Current.User.Identity.Name);
            targetComment.CreatedOn = DateTime.Now;
            targetComment.CommentBody = Html.Encode(request.CommentBody);

            return targetComment;
        }


        public virtual Comment MapCommentPageToComment(Comment targetComment, CommentPage commentPage)
        {
            if (targetComment == null || commentPage == null)
                return targetComment;

            targetComment.AuthorName = commentPage.CreatedBy;
            targetComment.Author = userDataProvider.GetUserData(commentPage.CreatedBy);
            targetComment.CommentBody = (commentPage.CommentBody != null ? commentPage.CommentBody.ToString() : string.Empty);
            targetComment.CreatedOn = commentPage.Created;

            return targetComment;
        }
    }
}
